<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * 加密解密函数
 * @param        $string
 * @param string $operation
 * @param string $key
 * @param int    $expiry
 * @return bool|mixed|string
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    if ($operation == 'DECODE') {
        $string = str_replace('[a]', '+', $string);
        $string = str_replace('[b]', '&', $string);
        $string = str_replace('[c]', '/', $string);
    }
    $ckey_length   = 4;
    $key           = md5($key ? $key : 'todo');
    $keya          = md5(substr($key, 0, 16));
    $keyb          = md5(substr($key, 16, 16));
    $keyc          = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey      = $keya . md5($keya . $keyc);
    $key_length    = strlen($cryptkey);
    $string        = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result        = '';
    $box           = range(0, 255);
    $rndkey        = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j       = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp     = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a       = ($a + 1) % 256;
        $j       = ($j + $box[$a]) % 256;
        $tmp     = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        $ustr = $keyc . str_replace('=', '', base64_encode($result));
        $ustr = str_replace('+', '[a]', $ustr);
        $ustr = str_replace('&', '[b]', $ustr);
        $ustr = str_replace('/', '[c]', $ustr);
        return $ustr;
    }
}

function fill_option($list, $data = null)
{
    $html = "";
    if (is_array($list)) {
        foreach ($list as $key => $val) {
            if (is_array($val)) {
                $id   = $val['id'];
                $name = $val['title'];
                if (empty($data)) {
                    $selected = "";
                } else {
                    $selected = "selected";
                }
                $html = $html . "<option value=\"{$id}\" $selected>{$name}</option>\r\n";
            } else {
                if ($key === $data) {
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $html = $html . "<option value=\"{$key}\" $selected>{$val}</option>\r\n";
            }
        }
    }

    echo $html;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}
function tree_to_list($tree, $level = 0, $pk = 'id', $pid = 'pid', $child = '_child')
{
    $list = array();
    if (is_array($tree)) {
        foreach ($tree as $val) {
            $val['level'] = $level;
            if (isset($val['_child'])) {
                $child = $val['_child'];
                if (is_array($child)) {
                    unset($val['_child']);
                    $list[] = $val;
                    $list   = array_merge($list, tree_to_list($child, $level + 1));
                }
            } else {
                $list[] = $val;
            }
        }
        return $list;
    }
}

//递归重组分类信息为多维数组
function cate_merge($cate, $access = null, $parentid = 0, $field1 = 'id', $field2 = 'pid')
{
    $arr = array();
    foreach ($cate as $v) {
        if (is_array($access)) {
            $v['access'] = in_array($v[$field1], $access) ? 1 : 0;
        }
        if ($v[$field2] == $parentid) {
            $v['child'] = cate_merge($cate, $access, $v[$field1], $field1, $field2);
            $arr[]      = $v;
        }
    }
    return $arr;
}


/**
 * [get_client_ip 获取客户端ip]
 * @Author   雨夜
 * @DateTime 2019-01-08
 * @return   [type]     [description]
 */
function get_client_ip()
{
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : '';
    return $res;
}

/**
 * [http_request 发起curl请求]
 * @Author   雨夜
 * @DateTime 2018-12-20
 * @param    [type]     $url [description]
 * @return   [type]          [description]
 */
function http_request($url){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_HEADER,0);
    $output = curl_exec($ch);
    if($output === FALSE ){
        return false;
    }
    curl_close($ch);
    return $output;
}

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000; //approximate radius of earth in meters
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

/**
 * [将Base64图片转换为本地图片并保存]
 * @param  [Base64] $base64_image_content [要保存的Base64]
 * @param  [目录] $path [要保存的路径]
 */
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        
        $type = $result[2];
        $new_file = $path."/";
        
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file);
        }
        $imgname = time().".{$type}";
        $new_file = $new_file.$imgname;
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return $new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}